import {
  Component,
  HostBinding,
  HostListener,
  Input,
  OnInit,
  OnDestroy,
  ElementRef,
  AfterContentChecked,
  ViewChild,
  TemplateRef,
} from '@angular/core';

import { SelectStoreService, SelectOption } from './select-store.service';

@Component({
  selector: 'fui-select-option',
  templateUrl: './select-option.component.html',
})
export class SelectOptionComponent implements OnInit, OnDestroy, AfterContentChecked {
  @HostBinding('class.fui-select-option') true;

  @HostBinding('class.active') get activeClass() {
    return this.option.selected;
  }

  @HostBinding('attr.disabled') get attrDisabled() {
    return this.disabled;
  }

  @ViewChild(TemplateRef) template: TemplateRef<void>;

  /** Data value. */
  @Input() value: any;

  /** Display label. */
  @Input() label: any;

  /** Disable single option. */
  @Input() disabled = false;

  option: SelectOption;

  get viewValue() {
    return (this.elementRef.nativeElement as HTMLElement).textContent;
  }

  get showCheckbox() {
    return this.store.mode === 'multiple';
  }

  @HostListener('click', ['$event']) clickHandler(event: MouseEvent) {
    event.preventDefault();
    if (!this.disabled) {
      this.store.toggleSelect(this.option);
    }
  }

  constructor(
    public store: SelectStoreService,
    private elementRef: ElementRef,
  ) {

  }

  ngOnInit() {
    this.option = new SelectOption(this.value, this.label);
    this.store.addOption(this.option);
  }

  ngAfterContentChecked() {
    // 如果没有设置label，则用viewValue来作为option的label。
    // 我们只更新select为true的option label，来尽量减少对dom的访问，textContent也不会触发reflow。
    if (this.label === undefined || this.label === null) {
      if (this.option.selected) {
        this.store.updateOption(this.option, {label: this.viewValue});
      }
    }
  }

  ngOnDestroy() {
    this.store.removeOption(this.option);
  }

}
